using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Text;

namespace Impact.Web.Foundation.Controls
{
    /// <summary>
    /// creates a javascript block containing all Server Controls on the page
    /// </summary>
    public class ServerVars : System.Web.UI.UserControl
    {

        /// <summary>
        /// write out the javascript
        /// </summary>
        protected override void Render( System.Web.UI.HtmlTextWriter writer )
        {
            base.Render( writer );

            writer.WriteLine( "\t<script type=\"text/javascript\">" );
            writer.WriteLine( "\t\tvar ServerControls = {" );

            List<Control> controls = GetPageControls( this.Page );
            StringBuilder scriptBuilder = new StringBuilder();

            foreach ( Control control in controls )
            {
                if ( !string.IsNullOrEmpty( control.ID ) )
                    scriptBuilder.AppendFormat( "\t\t\t{0}: $(\"#{1}\"),\r\n", control.ID, control.ClientID );
            }

            string script = scriptBuilder.ToString();
            if ( script.Length > 0 )
            {
                // get ride of the last comma for IE compat
                script = script.Remove( script.LastIndexOf( ',' ), 1 );
            }

            writer.WriteLine( script );
            writer.WriteLine( "\t\t};" );
            writer.WriteLine( "\t</script>" );

        }

        private List<Control> GetPageControls( Control root )
        {
            List<Control> controls = new List<Control>();
            foreach ( Control c in root.Controls )
            {
                controls.Add( c );
                if ( c.HasControls() )
                {
                    controls.AddRange( GetPageControls( c ) );
                }
            }
            return controls;
        }

    }
}
